const http = require("http");
const fs = require("fs");
const url = require("url");
const template = require("art-template");

const comments = [
    {
        name: "小明",
        message: "你好啊",
        dateTime: "2019-07-01"
    }, {
        name: "小明2",
        message: "你好啊",
        dateTime: "2019-07-01"
    }, {
        name: "小明3",
        message: "你好啊",
        dateTime: "2019-07-01"
    }, {
        name: "小明4",
        message: "你好啊",
        dateTime: "2019-07-01"
    }, {
        name: "小明5",
        message: "你好啊",
        dateTime: "2019-07-01"
    }
];

http
    .createServer((req, res) => {
        // 使用url.parse将路径解析成一个方便操作的对象
        var parseObj = url.parse(req.url, true);

        // 获取不包含？后面的内容
        var pathname = parseObj.pathname;

        // const url = req.url;
        if (pathname === "/") {
            fs.readFile("./view/index.html", (err, data) => {
                if (err) {
                    return res.end("404 Not Found")
                }
                var htm = template.render(data.toString(), {comments: comments});
                res.end(htm)
            });

        } else if (pathname === "/pinglun") {
            // 获取表单提交的数据

            // 将 日期 和 用户提交的数据放入数组中

            // 跳转到首页
            var comment = parseObj.query;
            comment.dateTime = "2019-07-01";
            comments.unshift(comment);
            res.statusCode = 302;
            res.setHeader("Location","/");
            res.end()


        } else if (pathname === "/post") {
            fs.readFile("./view/post.html", (err, data) => {
                if (err) {
                    res.end("404 Not Found.")
                }
                res.end(data)
            })
        } else if (pathname.indexOf("/public/") === 0) {
            // console.log(url)
            fs.readFile("." + pathname, (err, data) => {
                if (err) {
                    res.end("Can not found " + pathname)
                }
                res.end(data)
                // console.log(files)
            })
        } else {
            fs.readFile("./view/404.html", (err, data) => {
                res.end(data)
            })
        }
    })
    .listen(2500, () => {
        console.log("this server is running at http://127.0.0.1:2500")
    });
